// pages/company-info/company-info.js
import { Factory } from "../../models/factory";
import areaList from "../../utils/area-list";
import { config } from "../../config/config";
import { UserInfo } from "../../models/userinfo";
import Toast from "../../miniprogram_npm/@vant/weapp/toast/toast";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    areaList,
    show: false,
    show2: false,

    address: "",
    person: "",
    personTel: "",
    introduction: "",
    area: "请选择省、市、区",
    avatarUrl: "",
    fileList: [],
    code: [],
    id: "",
    info: null,
    typeName: "",
    typeId: "",
    productList: [],
    Status: 0,
    PopedomId: "",
    autosize: { maxHeight: 300, minHeight: 200 }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let data = new UserInfo();
    this.data.userInfo = data.getUserInfo();
    this.setData({
      userInfo: data.getUserInfo()
    });
    this.init();
  },
  async init() {
    let postData = {
      Search: { all: true, userId: this.data.userInfo.Id, keyword: null },
      PageIndex: 1,
      PageRows: 10000,
      SortField: "Order",
      SortType: "asc"
    };
    const data2 = await Factory.GetDataListClassify(postData);
    data2.Data.map(item => {
      item.name = item.Name;
    });
    this.data.productList = data2.Data;
    this.setData({
      productList: data2.Data
    });
    postData.SortField = "Id";
    const data = await Factory.GetDataList(postData);

    if (data.Data.length > 0) {
      this.data.info = data.Data[0];

      let Imgs = this.data.info.Imags.split(",");
      let fileList = [];
      Imgs.forEach(item => {
        fileList.push({
          url: item
        });
      });

      // this.Status = this.info.Status;
      // this.PopedomId = this.info.PopedomId;
      // this.id = this.info.Id;

      // this.person = this.info.ContactInfo;

      // this.introduction = this.info.Content;
      // this.fileList = fileList;

      // this.address = this.info.Location;

      // this.personTel = this.info.Contactfs;
      this.setData({
        info: data.Data[0],
        Status: this.data.info.Status,
        PopedomId: this.data.info.PopedomId,
        id: this.data.info.Id,
        person: this.data.info.ContactInfo,
        introduction: this.data.info.Content,
        fileList,
        address: this.data.info.Location,
        personTel: this.data.info.Contactfs
      });

      this.data.typeId = this.data.info.Demandclassifyid;
      this.findTypeById(this.data.info.Demandclassifyid);

      this.data.code = this.data.info.Title.split(",");
      this.findAreaByCode(this.data.code);
    }
  },
  addrChange(e) {
    this.data.address = e.detail;
  },
  personChange(e) {
    this.data.person = e.detail;
  },
  telChange(e) {
    this.data.personTel = e.detail;
  },
  intChange(e) {
    this.data.introduction = e.detail;
  },
  onSelect(e) {
    console.log(e);
    // this.typeName = e.name;
    this.data.typeId = e.detail.Id;
    // this.show2 = false;
    this.setData({
      typeName: e.detail.name,
      show2: false
    });
  },
  findTypeById(id) {
    const data = this.data.productList.find(item => {
      return item.Id == id;
    });

    // this.typeName = data.Name;
    this.setData({
      typeName: data.Name
    });
    return data.Name;
  },
  findAreaByCode(codes) {
    let area = [];
    if (codes.length > 0) {
      for (let key in this.data.areaList.province_list) {
        if (key == codes[0]) {
          area.push(areaList.province_list[key]);
        }
      }
    }
    if (codes.length == 2) {
      for (let key in this.data.areaList.city_list) {
        if (key == codes[1]) {
          area.push(areaList.city_list[key]);
        }
      }
    }
    this.setData({
      area: area.join("/")
    });
  },
  // async afterRead(file) {
  //   let formData = new FormData();
  //   formData.append("fileList", file.file);
  //   const data = await UploadFileByForm(formData);

  //   let len = this.fileList.length;
  //   this.fileList[len - 1].url = data.url;
  // },
  afterRead(e) {
    let that = this;
    let file = e.detail.file;

    wx.uploadFile({
      url: `${config.apiBaseUrl}Base_Manage/Upload/UploadFileByForm`, // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: "file",
      // formData: { user: 'test' },
      success(res) {
        // 上传完成需要更新 fileList
        console.log(res.data);
        let data = JSON.parse(res.data);
        console.log(data.url);
        const { fileList = [] } = that.data;
        fileList.push({ ...file, url: data.url });
        that.setData({ fileList });
      }
    });
  },
  delImg(e) {
    this.setData({
      fileList: []
    });
  },
  selectType() {
    console.log("selectType");
    this.setData({
      show2: true
    });
  },
  selectArea() {
    this.setData({
      show: true
    });
    // this.show = true;
  },
  cancel() {
    console.log("cancel");
    this.setData({
      show: false
    });
  },
  confirm(val) {
    console.log(val);
    let code = [];
    let area = [];
    let arr = val.detail.values;
    if (arr.length > 0) {
      arr.forEach(item => {
        if (item.code) {
          code.push(item.code);
          area.push(item.name);
        }
      });
    }
    this.setData({
      code,
      area: area.join("/"),
      show: false
    });
    // this.code = code;
    // this.area = area.join("/");
    // this.show = false;
  },
  async submit(val) {
    let list = [];
    this.data.fileList.forEach(item => {
      list.push(item.url);
    });
    let Imags = list.join(",");

    let postData = {
      Id: this.data.id,
      CreatorId: this.data.userInfo.Id,
      CreateTime: new Date(),
      User_id: this.data.userInfo.Id,
      Title: this.data.code.join(","),
      Status: this.data.Status,
      Content: this.data.introduction,
      Updatetime: new Date(),
      Location: this.data.address,
      ContactInfo: this.data.person,
      Demandclassifyid: this.data.typeId,
      PopedomId: this.data.PopedomId,
      Imags: Imags,
      Contactfs: this.data.personTel
    };
    const data = await Factory.SaveData(postData);
    console.log(data);
    if (data.Success) {
      Toast("保存成功");
    } else {
      Toast(data.Msg);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {}
});
